<template>
  <MainContentSearchBarWrapper>
    <el-date-picker
      v-model="dateMonth"
      type="month"
      @change="monthChange()"
      placeholder="请选择月份"
      :clearable="false"
    />
  </MainContentSearchBarWrapper>
  <el-table
    border
    :height="tableHeight"
    v-table-infinite-scroll="load"
    :header-cell-style="{ background: '#F5F6F9', height: '98px' }"
    v-loading="loading"
    :data="state.tableData"
    :span-method="arraySpanMethod"
    :key="Math.random()"
    style="width: 100%"
    ref="elTableRef"
  >
    <el-table-column
      min-width="52px"
      v-for="(item, index) in state.currentMonthDayList"
      :key="index"
      :label="item.day"
      align="center"
    >
      <template #header>
        <span class="header-day" :class="{ 'header-day-active': '' }">{{
          item.day
        }}</span>
        <div class="header-week">{{ item.week }}</div>
      </template>
      <template #default="scope">
        <span
          class="process-content"
          :style="`background:${bgColorList[scope.row.status]};color:${
            textColorList[scope.row.status]
          };`"
          v-if="new Date(scope.row.publishTime).getDate() == scope.column.label"
          @click="$router.push(`/flow/auto/marketingProcess/processDetail?id=${scope.row.id}`)"
        >

          <el-popover
            placement="top-start"
            :title="processNameList[scope.row.status]"
            trigger="hover"
            :content="scope.row.name"
          >
            <template #reference>
              <img :src="imgList[scope.row.status]" alt="" />
            </template>
          </el-popover>
          <span>{{ scope.row.name }}</span></span
        >

      </template>
    </el-table-column>
  </el-table>
</template>
<script lang="ts" setup>
import moment from "moment";
import CustomerApi from "@/api/customerApi.js";
import IconSuccess from "@/assets/images/icon-success.png";
import IconPause from "@/assets/images/icon-pause.png";
import IconFinish from "@/assets/images/icon-Finish.png";

const state = reactive({
  currentMonthDayList: [] as any[],
  monthDayList: [] as any[],
  tableData: [] as any[],
});
const elTableRef = ref()
const isLoad = ref(false)
const loading = ref(false);
const week = ref(["日", "一", "二", "三", "四", "五", "六"]);
const formData = ref({
  yearDateStr: "",
  calendarNum: "",
  currentPage: 1,
  showCount: 30,
});

const bgColorList = ref({
  1: "#F0F9EB",
  2: "#F0F9EB",
  "-1": "#FFF8E5",
  "-2": "#E8F2FF",
});
const textColorList = ref({
  1: "#67C23A",
  2: "#67C23A",
  "-1": "#FFBF00",
  "-2": "#3E61A9",
});
const imgList = ref({
  1: IconSuccess,
  2: IconSuccess,
  "-1": IconPause,
  "-2": IconFinish,
});
const processNameList = ref({
  1: '运行中',
  2: '运行中',
  "-1": '已暂停',
  "-2": '已完成',
})
const tabScrollTop = ref(0)
const tableHeight = ref("500");
const nowYear = ref(new Date().getFullYear());
const nowMonth = ref(new Date().getMonth() + 1);
const dateMonth = ref(`${nowYear.value}-${nowMonth.value}`);
const monthChange = () => {
  tabScrollTop.value = 0
  isLoad.value = false
  formData.value.currentPage = 1
  getMonthDate(true);
};

interface SpanMethodProps {
  row: User;
  columnIndex: number;
}
const setDate = (time1: string, time2: string)=>{
  if((moment(parseInt(time1)).format('YYYY-MM-DD'))==(moment(parseInt(time2)).format('YYYY-MM-DD'))) {
    return true
  }
  return false

}
// 列合并
const arraySpanMethod = ({ row, columnIndex }: SpanMethodProps) => {
  let startTime = ref(new Date(row.publishTime).getDate());
  let endTime = ref(new Date(row.invalidTime).getDate());
  if (columnIndex == startTime.value - 1) {
    return {
      rowspan: 1, //从第一列第二行开始 向下合并一行
      colspan: endTime.value - startTime.value + 1, //控制列合并
    };
  }
  //第二列第三行内容已合并到第二行 需将合并的内容删除
};


const getMonthDate = (isChange: boolean | undefined) => {
  loading.value = true;
  state.monthDayList = [];
  const date = new Date(dateMonth.value);
  console.log(date);
  const year = date.getFullYear();
  const month =
    Number(date.getMonth() + 1) >= 10
      ? date.getMonth() + 1
      : `0${date.getMonth() + 1}`;
  const numMonth = date.getMonth() + 1;
  formData.value.calendarNum = String(numMonth);
  const day = new Date(year, numMonth, 0);
  const dayCounts = day.getDate(); //  指定月份天数
  for (var i = 0; i < dayCounts; i++) {
    state.monthDayList.push({
      day: `${i + 1}`,
      week: week.value[new Date(`${year}-${month}-${i + 1}`).getDay()],
    });
  }
  state.currentMonthDayList = state.monthDayList;
  formData.value.yearDateStr = `${year}-${month}-01`;
  console.log(formData.value.yearDateStr);
  console.log("state.currentMonthDayList", state.currentMonthDayList);
  // 请求数据
  getCalenderList(isChange);
};
// 滚动加载
const load = (scrollTop: any) => {
  console.log('elTableRef.value---------------elTableRef.value',elTableRef.value);
  console.log('tabScrollTop.value',tabScrollTop.value);
  console.log('load-----scrollTopscrollTopscrollTop',scrollTo);
  if(isLoad.value) {
    return
    // isLoad.value  = false
  }
  tabScrollTop.value = scrollTop
  // let tbody = querySelector(".el-scrollbar__wrap");


  formData.value.currentPage++;
  loading.value = true;
  getCalenderList(false);
};


const setScrollTo = ()=> {
  nextTick(()=>{
    elTableRef.value.scrollTo([500,500])
  })
}



const getCalenderList = async (isChange: boolean | undefined) => {
  let rs = await CustomerApi.getCalenderList(formData.value);
  if (rs.code === 200) {
    console.log("rs", rs);
    if(rs.payload.length == 0) {
      isLoad.value  = true
    }
    if (isChange) {
      state.tableData = rs.payload;
      console.log('state.tableData-isChange ',state.tableData );
    } else {
      state.tableData = [...state.tableData, ...rs.payload];
      console.log('state.tableData-else ',state.tableData );
    }
    elTableRef.value.setScrollTop(tabScrollTop.value)
     nextTick(()=>{
      elTableRef.value.setScrollTop(tabScrollTop.value)
    })
    setTimeout(() => {
      elTableRef.value.setScrollTop(tabScrollTop.value)
    }, 0);
    loading.value = false;
    console.log("tableData.values", state.tableData);
  }
  // loading.value = false;
};

onMounted(() => {
  getMonthDate(true);
});
interface User {
  createTime: 1649731911543;
  cycleDayTime: "00:00:00";
  cycleType: 3;
  cycleValue: 1;
  deleted: 0;
  enterCount: 12;
  id: 12;
  invalidTime: 1651248000000;
  limitCount: 0;
  marketingJourneyInfoId: 0;
  marketingJourneyStrategyId: 0;
  merchantId: 2;
  middleAccessStatus: 1;
  name: "数据统计";
  publishTime: 1649731820000;
  reachCount: 6;
  startType: 1;
  status: -2;
  updateTime: 1649731913092;
  userGroupId: 2;
  userGroupSymbol: "测试统计数据";
}
</script>
<style lang="scss" scoped>
.process-content {
  position: relative;
  display: block;
  width: 100%;
  line-height: 54px;
  color: #fff;
  border-radius: 27px;
  margin-top: 10px;
  margin-bottom: 10px;
  // padding-left: 45px;
  cursor: pointer;
  position: relative;
  img {
    position: absolute;
    left: 6px;
    top: 6px;
    width: 42px;
    height: 42px;
  }
  span {
    // width: ;
    display: block;
    // padding-left: 20px;
    margin: 0 20px 0 55px;
    overflow: hidden; //溢出隐藏
    white-space: nowrap; //禁止换行
    text-overflow: ellipsis; //...
  }
}
.header-day {
  display: block;
  height: 32px;
  width: 32px;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  line-height: 32px;
  border-radius: 50%;
}
.header-week {
  margin-top: 10px;
  height: 30px;
  font-size: 16px;
  font-weight: 400;
  color: #666666;
  line-height: 30px;
}
.header-day-active {
  background: #001e70;
}

:deep(.el-table__row:hover > td) {
  background-color: unset !important;
}
// :deep(.el-table__body .el-table__row .el-table__cell) {
//   border-bottom: none;
// }
:deep(.el-table__body .el-table__cell .cell){
  padding: 0;
}
// .process-name {
//   color: red;
//   position: absolute;

// }

.el-table {
  margin-top: 20px
}
</style>
